package com.voja.salonschedule.customers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;

import com.voja.salonschedule.data.Customer.CustomerItem;

import android.widget.Filter;

public class ListFilter extends Filter {
    
    Adapter adapter;
    boolean autocomplete;
    
    public ListFilter(Adapter adapter, boolean autocomplete) {
        this.adapter = adapter;
        this.autocomplete = autocomplete;
    }
    
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        
        synchronized (results) {
            Locale locale = Locale.getDefault();
            
            if (constraint != null) {
                ArrayList<CustomerItem> lstResult = new ArrayList<CustomerItem>();
                boolean condition = false;
                
                adapter.keyword = constraint.toString().toLowerCase(locale);
                CustomerItem customer;
                for (int i=0; i<adapter.customers.size(); i++) {
                    customer = adapter.customers.get(i);
                    condition = customer.name.toLowerCase(locale).matches(".*" + adapter.keyword + ".*");
                    if (condition) {
                        lstResult.add(customer);
                    }
                }
                
                results.values = lstResult;
                results.count  = lstResult.size();
                
            } else if(!autocomplete && (constraint == null || constraint == "")) {
                results.values = adapter.customers;
                results.count  = adapter.customers.size();
            }
            
            return results;
        }
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        if (results.count > 0) {
            adapter.customersFiltered.clear();
            adapter.customersFiltered.addAll(collect(results.values));
            adapter.notifyDataSetChanged();
        } else {
            adapter.notifyDataSetInvalidated();
        }
    }
    
    @SuppressWarnings("unchecked")
    public Collection<? extends CustomerItem>collect(Object customers) {
        return (Collection<CustomerItem>)customers;
    }

}
